package com.usian.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usian.behavior.entity.ApReadBehavior;
import com.usian.behavior.mapper.ApReadBehaviorMapper;
import com.usian.behavior.service.IApReadBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.threadlocal.UserThreadLocalUtils;
import com.usian.model.behavior.dtos.ReadBehaviorDto;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.ResourceBundle;

/**
 * <p>
 * APP阅读行为表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-07-18
 */
@Service
public class ApReadBehaviorServiceImpl extends ServiceImpl<ApReadBehaviorMapper, ApReadBehavior> implements IApReadBehaviorService {
    /**
     * 储存阅读数据
     * @param dto
     */
    @Override
    public void saveReadBehavior(ReadBehaviorDto dto) {
        //是否用户登录
        boolean isUser=false;
        //获取当前用户的信息
        Integer userId = UserThreadLocalUtils.getUserId();
        //机械码id
        String equipmentId = dto.getEquipmentId();
        //用户id和机械码不能为空
        if (userId==null && equipmentId==null){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"用户id和机械码不能为空");
        }
        //登录为true
        if (userId!=null && userId!=0){
            isUser=true;
        }
        //查询是否有当前阅读行为
        LambdaQueryWrapper<ApReadBehavior> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApReadBehavior::getArticleId,dto.getArticleId());
        //如果user存在
        if (isUser){
            lambdaQueryWrapper.eq(ApReadBehavior::getApUserId,userId);
        }else {
            //不存在进行主机号查询
            lambdaQueryWrapper.eq(ApReadBehavior::getEquipmentId,equipmentId);
        }
        ApReadBehavior readBehavior = getOne(lambdaQueryWrapper);
        //如果readBehavior==null
        if (readBehavior==null){
            //进行添加
            readBehavior.setCount(dto.getCount());
            readBehavior.setArticleId(dto.getArticleId());
            readBehavior.setPercentage(dto.getPercentage());
            if (isUser){
                lambdaQueryWrapper.eq(ApReadBehavior::getApUserId,userId);
            }else {
                lambdaQueryWrapper.eq(ApReadBehavior::getEquipmentId,equipmentId);
            }
            readBehavior.setLoadDuration(dto.getLoadDuration());
            readBehavior.setReadDuration(dto.getReadDuration());
            readBehavior.setCreatedTime(new Date());
            save(readBehavior);
        }else {
            //去进行修改
            readBehavior.setUpdatedTime(new Date());
            readBehavior.setCount(readBehavior.getCount()+dto.getCount());
            updateById(readBehavior);
        }

    }
}
